﻿using System;
using System.Threading;

namespace FscNET.Apm
{
    public sealed class CountdownTimer : IDisposable
    {
        // Fields
        private AsyncResult m_asyncResult;
        private Timer m_timer;

        // Methods
        public CountdownTimer()
        {
            m_timer = new Timer(CountdownDone);
        }

        public IAsyncResult BeginCountdown(int ms, AsyncCallback callback, object state)
        {
            Interlocked.Exchange(ref m_asyncResult, new AsyncResult(callback, state, this));
            m_timer.Change(ms, -1);
            return m_asyncResult;
        }

        private void CountdownDone(object state)
        {
            m_asyncResult.SetAsCompleted(null, false);
        }

        public void Dispose()
        {
            if (m_timer != null)
            {
                m_timer.Dispose();
                m_timer = null;
            }
        }

        public void EndCountdown(IAsyncResult result)
        {
            ((AsyncResult)result).EndInvoke();
        }
    }

}
